<?php
namespace app\backend\controller;

use app\backend\model\sys_user;
use think\Session;
use think\Validate;

class Index extends Base
{
    public function index()
    {
        $user = new sys_user();
        $user = $user->getLoginUser();
        $this->view->assign("user",$user);
        return $this->view->fetch();
    }
    public function login(){
        return $this->view->fetch();
    }
    public function postlogin(){
        $params = $this->request->param();
        // 验证参数
        $rule = [
            'username'  => 'require|max:20',
            'password'   => 'require|max:20'
        ];
        $msg = [
            'username.require' => '用户名必须',
            'username.max'     => '名称最多不能超过20个字符',
            'password.require'   => '密码不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($params,$rule);
        $error = $validate->getError();
        if(!$result){
            return json($this->buildFailed(-1,$error));
        }
        // 查询数据库
        $user1 = new sys_user();
        $user2 = $user1->login($params);
        if($user2){
            $user1->setSessionUser($user2);
            return json($this->buildSuccess(1,"登录成功",$user2));
        }else{
            return json($this->buildFailed(0,"用户名或者密码错误"));
        }
    }
}
